package com.example.t9lv0;

import java.net.URL;
import java.util.Arrays;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.util.List;
import java.util.ArrayList;

public class HelloController {

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private TextField arrTF;

    @FXML
    private Button clearBtn;

    @FXML
    private Label resLabel;

    @FXML
    private Button solveBtn;

    @FXML
    private TextField sumWeigthTF;

    @FXML
    void clearClick(ActionEvent event) {
        arrTF.setText("");
        sumWeigthTF.setText("");
    }

    @FXML
    void solveClick(ActionEvent event) {
        List<Integer> weights = Arrays.stream(arrTF.getText().split(" ")).map(Integer::parseInt).toList();
        int sumWeight = Integer.parseInt(sumWeigthTF.getText());
        List<List<Integer>> result = selectionCount(weights, sumWeight);
        resLabel.setText(result.toString());
    }

    @FXML
    void initialize() {
        assert arrTF != null : "fx:id=\"arrTF\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert clearBtn != null : "fx:id=\"clearBtn\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert resLabel != null : "fx:id=\"resLabel\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert solveBtn != null : "fx:id=\"solveBtn\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert sumWeigthTF != null : "fx:id=\"sumWeigthTF\" was not injected: check your FXML file 'hello-view.fxml'.";

    }


    public List<List<Integer>> selectionCount(List<Integer> weights, int sumWeight) {
        List<List<Integer>> result = new ArrayList<>();
        int n = weights.size();
        for (int i = 0; i < (1 << n); i++) {
            int totalWeight = 0;
            List<Integer> combination = new ArrayList<>();
            for (int j = 0; j < n; j++) {
                if ((i & (1 << j)) != 0) {
                    int weight = weights.get(j);
                    totalWeight += weight;
                    combination.add(weight);
                }
            }
            if (totalWeight == sumWeight) {
                result.add(combination);
            }
        }
        return result;
    }

}
